//
//  AIGirlMessageViewController.swift
//  AIGirl
//
//  Created by Rae on 2023/12/22.
//

import UIKit
import IQKeyboardManager
import SwiftEntryKit
class AIGirlMessageViewController: AIGirlBaseViewController {

    private var navView = AIGirlMessageNavView()
    private var bottomView = AIGirlMessageBottomView()
    private var settingView = AIGirlMessageSettingView()
    private lazy var backgroungView = c_make_ex(UIImageView.self)
        .mode(.scaleAspectFill).end()
    private lazy var giftView = AIGirlMessageGiftView()
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(AIGirlChatReceiveTextCell.self,AIGirlChatSentTextCell.self,AIGirlChatReceiveImgCell.self,AIGirlChatReceiveLoadingCell.self,AIGirlChatSentGiftCell.self)
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100.0
        return tableView
    }()
    private var currentLevel = "" //当前等级
    private var pageIndex = 1
    private var historyArray: [AIGirlMessageItemModel] = [AIGirlMessageItemModel]()
    private var isMore = false //是否有更多消息
    private var giftData: [AIGirlGiftItemModel]?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared().isEnabled = false
        loadData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared().isEnabled = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = .white
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true
        view.subviews {
            backgroungView
            navView
            bottomView
            tableView
        }
        
        backgroungView.fillContainer()
        navView.leading(0).trailing(0).top(.statusHeight).height(44.0)
        bottomView.leading(0).trailing(0).bottom(0).height(130.0)
        tableView.leading(0).trailing(0)
        tableView.Top == navView.Bottom
        tableView.Bottom == bottomView.Top
        
        tableView.cr.addHeadRefresh {
            if self.isMore {
                self.pageIndex += 1
            }
            self.updateChatHistory(isToBottom: false)
        }
        
        let isFirst = UserDefaultsManager.getBool(forKey: .isInChatRoom)
        if !isFirst {
            UserDefaultsManager.setBool(true, forKey: .isInChatRoom)
            request.start(.seeHi) { result in
                if result.isSuccessful {
                    self.pageIndex = 1
                    self.updateChatHistory(isToBottom: true)
                }
            }
        }
        
        navView.backClosure = {
            if let tabBarController = self.tabBarController {
                tabBarController.tabBar.isHidden = false
                tabBarController.selectedIndex = 1
            }
        }
        navView.settingClosure = { 
            self.settingView.updateGirlInfo()
            self.updateGirlInfo()
            self.animation.animation(show: self.settingView)
        }
        navView.levelClosure = {
            self.animation.animation(show: AIGirlMsgLevelDetailView())
        }
        
        bottomView.diamondClosure = {
            self.animation.animation(show: AIGirlMessagePremiumView())
        }
        bottomView.giftClosure = {
            self.animation.animation(show: self.giftView)
        }
        bottomView.phototClosure = { [weak self] in
            let askNum = UserDefaultsManager.getInt(forKey: .askPhoto)
            if askNum == 0 {
                guard let array = self?.giftData else { return }
                UserDefaultsManager.setInt(9, forKey: .askPhoto)
                self?.showGuidanceView()
            }
            self?.request.start(.askForPhotos,type: AIGirlResMessageModel.self,isLoading: false, completion: { result in
                if result.isSuccessful {
                    self?.pageIndex = 1
                    self?.updateChatHistory(isToBottom: true)
                }
            })
        }
        bottomView.sendClosure = { [weak self] msg in
            
            var askNum = UserDefaultsManager.getInt(forKey: .sendMsg)
            let fristAlert = UserDefaultsManager.getInt(forKey: .firstMessageAlert)
            if askNum < 10 {
                if GlobalTool.userModel?.rechargeCount == 1 {
                    askNum += 1
                    UserDefaultsManager.setInt(askNum, forKey: .sendMsg)
                }
            }else if askNum == 10 && GlobalTool.userModel?.rechargeCount == 1{
                if fristAlert != 1 {
                    UserDefaultsManager.setInt(1, forKey: .firstMessageAlert)
                    self?.showGuidanceView()
                }
            }
            
            let sendMsg = AIGirlMessageItemModel(msg: msg,who: 0)
            let loadingMsg = AIGirlMessageItemModel(type: 999,who: 1)
            self?.historyArray.append(sendMsg)
            self?.historyArray.append(loadingMsg)
            self?.tableView.reloadData()
            let newMessageIndexPath = IndexPath(row: (self?.historyArray.count ?? 1) - 1, section: 0)
            self?.tableView.scrollToRow(at: newMessageIndexPath, at: .bottom, animated: true)
            self?.bottomView.sendBtn.isUserInteractionEnabled = false
            self?.request.start(.aiGirlSendMsg(message: msg), type: AIGirlResMessageModel.self, isLoading: false, completion: { result in
                if result.isSuccessful, let model = result.model {
                    let levelS = String(model.current.level)
                    if levelS != self?.currentLevel {
                        self?.currentLevel = levelS
                        self?.showLevelAnimateView(level: levelS, content: model.current.levelName)
                    }
                    self?.pageIndex = 1
                    self?.updateChatHistory(isToBottom: true)
                    self?.bottomView.sendBtn.isUserInteractionEnabled = true
                }else{
                    self?.bottomView.sendBtn.isUserInteractionEnabled = true
                }
            })
        }
        settingView.changeInterestClosure = { [weak self] dataArray in
            let changeIntV = AIGirlMsgChangeInterestView()
            changeIntV.dataList = dataArray
            changeIntV.saveClosure = {
                self?.request.start(.getUserInterests(isPart: true, type: 1, userId: GlobalTool.userModel?.id ?? 0),type: AIGirlUserInterestModel.self) { result in
                    if result.isSuccessful, let model = result.model {
                        self?.bottomView.interestData = model.interests
                        self?.settingView.interestData = model.interests
                        self?.getAllinterests()
                        self?.animation.animation(show: self?.settingView)
                    }
                }
            }
            changeIntV.dismissClosure = {
                self?.animation.animation(show: self?.settingView)
            }
            self?.animation.animation(show: changeIntV)
        }
        settingView.changeAvatarClosure = { [weak self] in
            
            let changeVC = AIGirlChangeAiGirlViewController()
            changeVC.discoverClosure = {
                if let tabBarController = self?.tabBarController {
                    tabBarController.tabBar.isHidden = false
                    tabBarController.selectedIndex = 1
                }
            }
            changeVC.doneClosure = {
                let imgStr = UserDefaultsManager.getString(forKey: .girlAvatar)
                self?.backgroungView.loadImage(url: imgStr)
                self?.updateGirlInfo()
                self?.settingView.updateGirlInfo()
            }
            self?.present(changeVC, animated: true)
        }
        settingView.editGirlInfoClosure = { [weak self] in
            
            let editV = AIGirlMsgChangeNameView()
//            editV.loadAge()
            editV.saveClosure = { nameStr in
                let girlId = UserDefaultsManager.getInt(forKey: .girlId)
                let modelId = UserDefaultsManager.getInt(forKey: .modelId)
                self?.request.start(.setGirlName(girlId: girlId, modelId: modelId, name: nameStr)) { result in
                    if result.isSuccessful {
                        UserDefaultsManager.setString(nameStr, forKey: .grilName)
                        self?.settingView.updateGirlInfo()
                        self?.animation.animation(show: self?.settingView)
                    }
                }
            }
            editV.dismissClosure = {
                self?.animation.animation(show: self?.settingView)
            }
            self?.animation.animation(show: editV)
        }
        
        settingView.changeGirlPhotoDtosClosure = { [weak self] in 
            self?.updateGirlInfo()
            self?.pageIndex = 1
            self?.updateChatHistory(isToBottom: true)
        }
        
        giftView.sendGiftClosure = { [weak self] model in
            
            self?.sendGift(model: model)
        }
        
        //礼物列表
        request.start(.QueryGiftList, type: AIGirlGiftModel.self) { result in
            if result.isSuccessful, let model = result.model {
                self.giftData = model.gifts
                self.giftView.giftData = model.gifts
            }
        }
        
        updateChatHistory(isToBottom: true)
        
        NotificationCenter.default.addObserver(forName: .updateChatHistory, object: nil, queue: nil) { noti in
            self.pageIndex = 1
            self.updateChatHistory(isToBottom: false)
        }
                
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            if let coins = UserDefaultsManager.getString(forKey: .sendCoin), coins.count > 0 {
                if coins != "0" {
                    UserDefaultsManager.setInt(0, forKey: .isShowFirstAward)
                    UserDefaultsManager.removeForKey(forKey: .sendCoin)
                    let firstV = AIGirlLoginAwardView()
                    firstV.value = Int(coins) ?? 0
                    self.animation.animation(show: firstV)
                }
            }
        }
        
        NotificationCenter.default.addObserver(forName: UIApplication.keyboardWillShowNotification, object: nil, queue: nil) { [weak self] noti in
            guard let userInfo = noti.userInfo, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let rect = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
                return
            }
            UIView.animate(withDuration: duration) {
//                self?.updateToolHeight(self?.toolView.input_height ?? 0, editing: true)
//                print(self?.toolView.bottomConstraint?.constant)
                print(rect)
//                self?.toolView.bottomConstraint?.constant = -(rect.height + 10)
                self?.bottomView.bottomConstraint?.constant = -(rect.height)
            } completion: { _ in
//                self?.scrollToBottom()
    
            }
        }
        
        NotificationCenter.default.addObserver(forName: UIApplication.keyboardWillHideNotification, object: nil, queue: nil) { [weak self] noti in
            guard let userInfo = noti.userInfo, let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval, let _ = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
                return
            }
            UIView.animate(withDuration: duration) {
//                self?.updateToolHeight(0, editing: false)
                self?.bottomView.bottomConstraint?.constant = 0
            } completion: { _ in
//                self?.scrollToBottom()
            }
        }
    }
    
    private func showLevelAnimateView(level: String, content: String) {
//        if SwiftEntryKit.isCurrentlyDisplaying {
//            animation.animation(dismiss: nil) { [weak self] in
//                guard let strongSelf = self else { return }
//                strongSelf.showLevelAnimateView(level: level, content: content)
//            }
//            return
//        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.navView.animateView.type = level
            let animateV = AIGirlLevelAnimateView()
            animateV.type = level
            animateV.content = content
            self.animation.animation(show: animateV)
        }
    }
   
    private func showGuidanceView() {
        
        guard let array = self.giftData else { return }
        let randomNumber = Int.random(in: 0..<array.count)
        let model = array[randomNumber]
        let giftV = AIGirlGuidanceGiftView()
        giftV.giftModel = model
        giftV.sendGiftClosure = { [weak self] md in
            self?.sendGift(model: md)
            self?.animation.animation(dismiss: giftV)
        }
        self.animation.animation(show: giftV)
    }
    
    private func sendGift(model: AIGirlGiftItemModel){
        
        let sendMsg = AIGirlMessageItemModel(msg: model.preUrl, type: 2,who: 0)
        let loadingMsg = AIGirlMessageItemModel(type: 999,who: 1)
        self.historyArray.append(sendMsg)
        self.historyArray.append(loadingMsg)
        self.tableView.reloadData()
        let newMessageIndexPath = IndexPath(row: self.historyArray.count - 1, section: 0)
        self.tableView.scrollToRow(at: newMessageIndexPath, at: .bottom, animated: true)
        self.request.start(.aiGirlSendGift(id: model.id), type: AIGirlResMessageModel.self, isLoading: false, completion: { result in
            if result.isSuccessful, let model = result.model {
                let levelS = String(model.current.level)
                if levelS != self.currentLevel {
                    self.currentLevel = levelS
                    self.showLevelAnimateView(level: levelS, content: model.current.levelName)
                }
                self.pageIndex = 1
                GlobalTool.refreshUserInfo()
                self.updateChatHistory(isToBottom: false)
            }
        })
    }
}

extension AIGirlMessageViewController: UITableViewDelegate, UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return historyArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let model = historyArray[indexPath.row]
        if model.who == 1 {
            if model.type == 1 {
                let cell = tableView.cell(AIGirlChatReceiveImgCell.self, indexPath: indexPath)
                cell.msgModel = model
                return cell
            }else if model.type == 999 {
                let cell = tableView.cell(AIGirlChatReceiveLoadingCell.self, indexPath: indexPath)
                return cell
            }else{
                let cell = tableView.cell(AIGirlChatReceiveTextCell.self, indexPath: indexPath)
                cell.msgModel = model
                return cell
            }            
        }else{
            if model.type == 2 {
                let cell = tableView.cell(AIGirlChatSentGiftCell.self, indexPath: indexPath)
                cell.msgModel = model
                return cell
            }else{
                let cell = tableView.cell(AIGirlChatSentTextCell.self, indexPath: indexPath)
                cell.msgModel = model
                return cell
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let model = historyArray[indexPath.row]
        if model.who == 1 {
            if model.look{
                if model.vip && GlobalTool.userModel?.isVip.intValue ?? 0 > 0 {
                    GlobalTool.showVipInfoPage(dismissClosure: nil) {
                        self.pageIndex = 1
                        self.updateChatHistory(isToBottom: false)
                    }
                }else if model.coin > 0 && GlobalTool.userModel?.money ?? 0 < model.coin {
                    self.animation.animation(show: AIGirlMessagePremiumView())
                }else if model.coin > 0 && GlobalTool.userModel?.money ?? 0 >= model.coin {
                    self.request.start(.unlockMessage(id: model.photoId, type: 0), completion: { result in
                        if result.isSuccessful {
                            "success!".toast_success
                            GlobalTool.refreshUserInfo()
                            self.pageIndex = 1
                            self.updateChatHistory(isToBottom: false)
                        }
                    })
                }else if model.type == 0 {
                    GlobalTool.showVipInfoPage()
                }
            }else{
                if model.type == 1 {
                    
                    var photos = [AIGirlDiscoverDetailPicModel]()
                    var temp = 0
                    var index = 0
                    historyArray.forEach { md in
                        if md.who == 1 && md.type == 1 && !md.look{
                            index += 1
                            let picModel = AIGirlDiscoverDetailPicModel(downPrice: md.downloadCoin, id: md.photoId, image: md.msg)
                            photos.append(picModel)
                        }
                        if md.id == model.id {
                            temp = index - 1
                        }
                    }
                    let albumVC = AIGirlAlbumViewController()
                    albumVC.photoDtos = photos
                    albumVC.selIndex = temp
                    self.present(albumVC, animated: true)
                }
            }
        }
    }
}

//MARK: loadData
extension AIGirlMessageViewController {
    
    private func loadData(){
        //房间
        request.start(.chatWindow, type: AIGirlChatRoomModel.self) { result in
            if result.isSuccessful, let model = result.model {
                let orUrl = model.background
                let realUrl = String(orUrl.filter { $0 != "\t" })
                self.backgroungView.loadImage(url: realUrl)
                UserDefaultsManager.setInt(model.photoId, forKey: .bgPhototId)
                self.navView.model = model
                self.currentLevel = model.level
            }
        }

        //标签
        updateUserInterestLabel()
      
    }
    
    func getAllinterests(){
        if let userId = GlobalTool.userModel?.id {
            self.request.start(.interestsList(isPart: true, type: 1, userId: userId),type: AIGirlInterestModel.self) { result in
                
                if result.isSuccessful, let model = result.models {
                    self.settingView.allInterestData = model
                }
            }
        }
    }
    
    private func updateUserInterestLabel(){
        
        //感兴趣的标签
        request.start(.getUserInterests(isPart: true, type: 1, userId: GlobalTool.userModel?.id ?? 0),type: AIGirlUserInterestModel.self) { result in
            if result.isSuccessful, let model = result.model {
                self.bottomView.interestData = model.interests
                self.settingView.interestData = model.interests
                self.getAllinterests()
            }
        }
    }
    
    private func updateChatHistory(isToBottom: Bool){
        
        //聊天历史记录
        request.start(.chatHistory(num: pageIndex, size:20), type: AIGirlMessageModel.self, isLoading: false) { result in
            self.tableView.refresh_end()
            if result.isSuccessful, let model = result.model {
                if model.num * model.size < model.totalCount {
                    self.isMore = true
                }else{
                    self.isMore = false
                }
                if self.pageIndex == 1 {
                    self.historyArray = model.rows
                }else {
                    self.historyArray.append(contentsOf: model.rows)
                }
                self.historyArray = Array(self.historyArray.reversed())
                self.updateGirlInfo()
                self.tableView.reloadData()
                if self.historyArray.count > 0 && isToBottom{
                    let newMessageIndexPath = IndexPath(row: self.historyArray.count - 1, section: 0)
                    self.tableView.scrollToRow(at: newMessageIndexPath, at: .bottom, animated: true)
                }                
            }
        }
    }
    
    private func updateGirlInfo(){
        let girlId = UserDefaultsManager.getInt(forKey: .modelId)
        request.start(.girlDetailInfo(girlId: girlId), type: AIGirlDiscoverDetailModel.self, isLoading: false) { result in
            if result.isSuccessful, let model = result.model {
                self.settingView.photoDtos = model.photoDtos
            }
        }
    }
}
